package services

import (
	"net/http"

	"demo/enmu"
	"demo/models"
	"demo/pkg/database"
	"demo/pkg/middleware"
	"demo/utils"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func LoginPostService(c *gin.Context) {
	user := new(models.Userinfo)
	resp := models.GetDefaultResp()
	if err := c.ShouldBindJSON(&user); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	if ok, token ,user:= login(user.Email, user.Password); ok && token != "" &&user!=nil{
		utils.SetCookie(c, token)
		data:=models.ResponseLogin{
			Jwt:token,
			Role: user.Role,
		}
		resp.Data = data		
		c.JSON(http.StatusOK, resp)
	} else {
		resp.Code, resp.Msg = enmu.BAD_LOGIN_INFO_CODE, enmu.BAD_LOGIN_INFO_MSG
		c.JSON(http.StatusBadRequest, resp)
	}
}

func login(email, password string) (bool, string,*models.Userinfo) {
	user, err := database.GetUserinfoByEmail(email)
	if err != nil {
		logrus.Error("获取用户信息失败:", err)
		return false, "", nil
	}
	hashedPassword := utils.HashPassword(password, email)
	if hashedPassword != user.Password {
		return false, "",nil
	}
	token, err := middleware.CreateToken(user)
	if err != nil {
		logrus.Errorln("Token签名失败:", err)
		return false, "",nil
	}
	return true, token,user
}


